<template>
  <div class="login-container">
    <div class="login-form">
      <h2>用户登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-item">
          <input 
            v-model="loginForm.username" 
            type="text" 
            placeholder="用户名" 
            autocomplete="off"
          >
        </div>
        <div class="form-item">
          <input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="密码"
          >
        </div>
        <div class="form-item captcha-item">
          <input 
            v-model="loginForm.code" 
            type="text" 
            placeholder="验证码" 
            autocomplete="off"
          >
          <img 
            :src="captchaImage" 
            alt="验证码" 
            @click="refreshCaptcha"
            class="captcha-image"
          >
        </div>
        <div class="form-item remember-item">
          <label>
            <input 
              v-model="loginForm.rememberMe" 
              type="checkbox"
            > 记住密码
          </label>
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
    </div>
  </div>
</template>

<script>
import { getCaptcha, login } from '@/api/auth.js'
import { useAuthStore } from '@/stores/auth.js'
import { encrypt, decrypt } from '@/utils/crypto.js'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        code: '',
        uuid: '',
        rememberMe: false
      },
      captchaImage: '',
      retryCount: 0
    }
  },
  
  mounted() {
    this.refreshCaptcha()
    this.loadCredentials()
  },
  
  methods: {
    refreshCaptcha: function() {
      getCaptcha().then(response => {
        console.log('验证码响应:', response)
        // 直接使用返回的完整base64数据URI
        this.captchaImage = response.data.data.img
        this.loginForm.uuid = response.data.data.uuid
        this.loginForm.code = ''
        this.retryCount++
      }).catch(error => {
        console.error('获取验证码失败:', error)
        if (this.retryCount < 3) {
          setTimeout(() => {
            this.refreshCaptcha()
          }, 1000)
        } else {
          alert('获取验证码失败，请刷新页面重试')
        }
      })
    },

    loadCredentials: function() {
      const encryptedData = localStorage.getItem('encryptedCredentials')
      if (encryptedData) {
        try {
          const parsed = JSON.parse(encryptedData)
          // 检查是否过期 (7天)
          if (Date.now() > parsed.expireTime) {
            localStorage.removeItem('encryptedCredentials')
            return
          }

          // 使用日期和固定字符串生成密钥
          const key = this.generateKey()
          this.loginForm.username = decrypt(parsed.username, key)
          this.loginForm.password = decrypt(parsed.password, key)
        } catch (e) {
          console.error('解密凭据失败:', e)
          localStorage.removeItem('encryptedCredentials')
        }
      }
    },

    generateKey: function() {
      const date = new Date().toISOString().slice(0, 10) // YYYY-MM-DD
      return date + 'secret_key' // 简单示例，实际项目中应该使用更复杂的密钥
    },

    handleLogin: function() {
      // 表单校验
      if (!this.loginForm.username) {
        alert('请输入用户名')
        return
      }

      if (!this.loginForm.password) {
        alert('请输入密码')
        return
      }

      if (!this.loginForm.code) {
        alert('请输入验证码')
        return
      }

      if (!this.loginForm.uuid) {
        alert('验证码无效，请刷新页面重试')
        return
      }

      // 构造登录参数
      // const params = new URLSearchParams()
      // params.append('username', this.loginForm.username)
      // params.append('password', this.loginForm.password)
      // params.append('code', this.loginForm.code)
      // params.append('uuid', this.loginForm.uuid)
      const params = {
        username: this.loginForm.username,
        password: this.loginForm.password,
        code: this.loginForm.code,
        uuid: this.loginForm.uuid
      }
      login(params).then(response => {
        console.log('登录响应:', response);
        // 处理登录成功
        let token = response.data.data.token;
        if (token) {
          // 存储token
          const authStore = useAuthStore()
          authStore.setToken(token)
          // 如果选择了记住密码，则保存凭据
          if (this.loginForm.rememberMe) {
            this.saveCredentials()
          } else {
            // 清除已保存的凭据
            localStorage.removeItem('encryptedCredentials')
          }
          // 跳转到首页
          this.$router.push('/')
        } else {
          alert('登录失败：无效的令牌')
          this.refreshCaptcha()
        }
      }).catch(error => {
        console.error('登录失败:', error)
        alert('登录失败：' + (error.message || '未知错误'))
        this.refreshCaptcha()
      })
    },
    
    saveCredentials: function() {
      try {
        // 生成密钥
        const key = this.generateKey()
        // 加密用户名和密码
        const encryptedUsername = encrypt(this.loginForm.username, key)
        const encryptedPassword = encrypt(this.loginForm.password, key)
        // 保存到localStorage，设置7天过期时间
        const data = {
          username: encryptedUsername,
          password: encryptedPassword,
          expireTime: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天后过期
        }

        localStorage.setItem('encryptedCredentials', JSON.stringify(data))
      } catch (e) {
        console.error('保存凭据失败:', e)
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-item {
  margin-bottom: 20px;
}

.form-item input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.captcha-item {
  display: flex;
  gap: 10px;
}

.captcha-item input {
  flex: 1;
}

.captcha-image {
  height: 40px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.remember-item {
  display: flex;
  align-items: center;
}

.remember-item input {
  width: auto;
  margin-right: 8px;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.login-button:hover {
  background-color: #66b1ff;
}
</style>